//PhotoPreview 点击小图后的效果
import 'dart:io';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:mfkb/config/Config.dart';
import 'package:path_provider/path_provider.dart';
import 'package:photo_view/photo_view.dart';
import 'package:photo_view/photo_view_gallery.dart';
import 'package:toast/toast.dart';

class ImageShowServerWidget extends StatefulWidget {
  final int initialIndex;
  final List<dynamic> photoList;
  final PageController pageController;

  ImageShowServerWidget({this.initialIndex, this.photoList})
      : pageController = PageController(initialPage: initialIndex);

  @override
  _ImageShowServerWidgetState createState() => _ImageShowServerWidgetState();
}

class _ImageShowServerWidgetState extends State<ImageShowServerWidget> {
  int currentIndex;

  @override
  void initState() {
    currentIndex = widget.initialIndex;
    super.initState();
  }

  getPath() async{
    var dir = await getExternalStorageDirectory() ;
    String path = dir.path ;
    if(path.indexOf("Android") != -1){
      path = path.substring(0 , path.indexOf("/Android")) ;
    }
    if(path.indexOf("android") != -1){
      path = path.substring(0 , path.indexOf("/android")) ;
    }
    print(path) ;
    var d = Directory(path + "/mfkb") ;
    if(!d.existsSync()){
      d.createSync() ;
    }
    d = Directory(path + "/mfkb/image") ;
    if(!d.existsSync()){
      d.createSync() ;
    }
    return Directory(path+"/mfkb/image") ;
  }

  //图片切换
  void onPageChanged(int index) {
    setState(() {
      currentIndex = index;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      child: Stack(
        children: <Widget>[
          Positioned(
            child: GestureDetector(
              child: PhotoViewGallery.builder(
                scrollPhysics: const BouncingScrollPhysics(),
                onPageChanged: onPageChanged,
                itemCount: widget.photoList.length,
                pageController: widget.pageController,
                builder: (BuildContext context, int index) {
                  return PhotoViewGalleryPageOptions(
                    imageProvider: CachedNetworkImageProvider(
                      Config().getImgHost() + widget.photoList[index]["url"]
                    ) , 
                    minScale: PhotoViewComputedScale.contained * 0.6,
                    maxScale: PhotoViewComputedScale.covered * 1.1,
                    initialScale: PhotoViewComputedScale.contained,
                    gestureDetectorBehavior: HitTestBehavior.opaque
                  );
                },
              ),
              onTap: (){
                Navigator.of(context).pop() ;
              },
              onLongPress: () async{
                showDialog(
                  context: context ,
                  child:Center(
                    child: GestureDetector(
                      child: Container(
                        width: 100,
                        height: 40,
                        color: Colors.white ,
                        child: Center(
                          child: Text("下载" , style: TextStyle(
                            fontSize: 14 ,
                            color: Colors.black
                          ),),
                        ),
                      ),
                      onTap: () async{
                        var path = await getPath() ;
                        String file = path.path+"/"+DateTime.now().microsecond.toString()+widget.photoList[currentIndex]["url"].toString().substring(widget.photoList[currentIndex]["url"].toString().lastIndexOf(".")) ;
                        Response response = await new Dio().download(Config().getImgHost() + widget.photoList[currentIndex]["url"] , file) ;
                        if(response.statusCode == 200){
                          Toast.show("保存成功,$file", context) ;
                        }else{
                          Toast.show("保存失败，错误代码"+response.statusCode.toString(), context) ;
                        }
                        Navigator.of(context).pop() ;
                      },
                    ),
                  ) ,
                  // builder: (context){
                  //   return Container(
                  //     height: 100 ,
                  //     width: 200 ,
                  //     color: Colors.white ,
                  //   ) ;
                  // }
                ) ;
                
              },
            ),
          ),
          Positioned(
            left: 10,
            top: 60,
            child: GestureDetector(
              child: Row(
                children: <Widget>[
                  Icon(
                    Icons.close,
                    color: Colors.white,
                  ),
                 
                ],
              ),
              onTap: () {
                Navigator.pop(context);
              },
            ),
          ),
          Positioned(
              right: 10,
              bottom: 60,
              child: Row(
                children: <Widget>[
                  Text('${currentIndex + 1}',
                      style: TextStyle(
                          color: Colors.white,
                          fontSize: 18,
                          decoration: TextDecoration.none,
                          fontWeight: FontWeight.w300)),
                  Text('/',
                      style: TextStyle(
                          color: Colors.white,
                          fontSize: 18,
                          decoration: TextDecoration.none,
                          fontWeight: FontWeight.w300)),
                  Text('${widget.photoList.length}',
                      style: TextStyle(
                          color: Colors.white,
                          fontSize: 18,
                          decoration: TextDecoration.none,
                          fontWeight: FontWeight.w300))
                ],
              ))
        ],
      ),
    );
  }
}
